﻿using System;
using System.IO;
using System.Threading;
using System.Windows;
using SmallBasicFun.Tracking;

namespace SmallBasicFun
{
	public interface ICapture
	{
		void Capture(string filename, Window window);
	}

	public class FileSystemCapture : ICapture
	{
		public void Capture(string filename, Window window)
		{
			ArchiveFile(filename);
			using (var fileStream = File.Create(filename))
			{
				ScreenCapture.DrawDispatchedWindow(window, fileStream);
			}
		}

		public static void ArchiveFile(string filename)
		{
			ArchiveFile(filename, File.GetLastWriteTime(filename));
		}

		public static string ArchiveFile(string filename, DateTime time)
		{
			if (!File.Exists(filename))
			{
				return null;
			}

			var info = new FileInfo(filename);
			string archive = info.DirectoryName + @"\"  + ScreenCapture.ProctorArchivePath;

			if (!Directory.Exists(archive))
			{
				Directory.CreateDirectory(archive);
			}

			string date = String.Format("{0}_{1:00}_{2:00}_{3:00}_{4:00}_{5:00}", time.Year, time.Month, time.Day,
			                            time.Hour,
			                            time.Minute, time.Second);

			string fileExtension = info.Extension;
			string filenameStart = info.Name.Substring(0, info.Name.Length - fileExtension.Length);
			string archiveName = String.Format("{0}\\{1}.{2}{3}", archive, filenameStart, date, fileExtension);
			if (File.Exists(archiveName))
			{
				File.Delete(archiveName);
			}
			File.Move(filename, archiveName);

			return archiveName;
		}
	}
}